// 导入所需的模块
const express = require('express');
const path = require('path');
const cors = require('cors');
const fetch = require('node-fetch');

// 创建一个 Express 应用
const app = express();
const port = process.env.PORT || 3000;

// CORS 配置 - 允许所有跨域请求
const corsOptions = {
    origin: '*',
    methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    allowedHeaders: '*',
    credentials: true,
    optionsSuccessStatus: 200
};

// 启用 CORS 和 JSON 解析
app.use(cors(corsOptions));
app.use(express.json());

// 静态资源目录
app.use('/', express.static(__dirname));

// 代理 Ollama API 请求
app.post('/api/generate', async (req, res) => {
    try {
        console.log('Received request:', req.body);

        // 转发请求到 Ollama
        const response = await fetch('http://localhost:11434/api/generate', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                model: req.body.model || 'qwen2.5:7b',
                prompt: req.body.prompt,
                stream: false
            })
        });

        if (!response.ok) {
            throw new Error(`Ollama API responded with status: ${response.status}`);
        }

        const data = await response.json();
        console.log('Ollama response:', data);

        res.json({
            response: data.response
        });
    } catch (error) {
        console.error('Error calling Ollama:', error);
        res.status(500).json({
            error: error.message
        });
    }
});

// 启动服务器
app.listen(port, () => {
    console.log(`Server running at http://localhost:${port}`);
}); 